//
//  DrivingRecordVC.m
//  Zhiche-Carriage
//
//  Created by 王亚陆 on 16/11/2.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "DrivingRecordVC.h"
#import "DrivingRecordCell.h"
#import "RootViewController.h"
#import "Common.h"
#import <Masonry.h>
#import "NullDataView.h"
#import "WKProgressHUD.h"
#import <MJRefresh.h>
@interface DrivingRecordVC ()
{
    UIImageView * nav;
    Common * com;
    RootViewController * TabBar;
    UITableView * table;
    NullDataView * nullView;
    
    NSMutableArray * dataArr;
    int page ;
    int totalPage;
    

}

@property (nonatomic,strong) NSMutableDictionary *dic;


@end

@implementation DrivingRecordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = GrayColor;
    page = 1;
    totalPage = 1;
    
    nav = [self createNav:@"出车记录"];
    [self.view addSubview:nav];
    TabBar = [RootViewController defaultsTabBar];
    
    dataArr = [[NSMutableArray alloc]init];
    self.dic = [NSMutableDictionary dictionary];
    
    [self createTable];
    
    nullView = [[NullDataView  alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 64) andTitle:@"暂无记录" andImageName:@"no_recode"];
    nullView.backgroundColor = GrayColor;

    
    [self createDate];
}


-(void)createTable{
    
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, screenHeight - 64) style:UITableViewStylePlain];
    [table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    table.showsVerticalScrollIndicator = NO;
    table.showsHorizontalScrollIndicator = NO;
    table.delegate = self;
    table.dataSource = self;
    table.backgroundColor = GrayColor;
    [self.view addSubview:table];
    [table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left);
        make.top.mas_equalTo(nav.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(Main_Width, Main_height-64));
    }];
    [table.mj_header beginRefreshing];
    table.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    table.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    


}

-(void)downRefresh{
    
    [table.mj_header endRefreshing];
    [table.mj_footer endRefreshing];
    page = 1;
    [self createDate];
    NSLog(@"刷新");
}

-(void)upRefresh{
    
    if (page!=totalPage) {
        page ++;
        [table.mj_footer endRefreshing];
        
        [self createDate];

    }else{
        table.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [table.mj_header endRefreshing];
    NSLog(@"加载%d%d",page,totalPage);
}


-(void)createDate{
    
    
    int pageSize = 10;
    WKProgressHUD *hud = [WKProgressHUD showInView:self.view withText:@"加载中" animated:YES];
    NSString * string = [NSString stringWithFormat:@"%@?pageNo=%d&pageSize=%d",waybill_done_Url,page,pageSize];
    [Common requestWithUrlString:string contentType:@"application/json" finished:^(id responseObj){
                
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [hud dismiss:YES];
            dataArr = [NSMutableArray arrayWithArray:responseObj[@"data"][@"list"]];
            totalPage = [responseObj[@"data"][@"page"][@"totalPage"] intValue ];
            NSMutableArray * arr = [NSMutableArray arrayWithArray:responseObj[@"data"][@"list"]];
            if ([arr count]>0) {
                if (page == 1) {
                    [dataArr removeAllObjects];
                    dataArr = arr;
                }else{
                    for (int i=0; i<[arr count]; i++) {
                        [dataArr addObject:arr[i]];
                    }
                }
                [nullView removeFromSuperview];
            }else{
                [dataArr removeAllObjects];
                [self.view addSubview:nullView];
            }
            
            
            [self updateArr:dataArr];
            
            [table reloadData];
        });
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [hud dismiss:YES];
            
        });
    }];
    
}

-(void)updateArr:(NSMutableArray *)arr
{
    
    NSMutableArray *mutable = [NSMutableArray array];
    for (int i = 0; i < arr.count; i ++) {
        
        if ([mutable containsObject:arr[i][@"monthText"] ]) {
            
        } else {
            
            [mutable addObject:arr[i][@"monthText"]];

        }
        
    }
    
    for (int i = 0; i < mutable.count; i ++) {
        
        NSMutableArray *month = [NSMutableArray array];
        
        for (int j = 0 ; j < arr.count; j ++) {
            if ([arr[j][@"monthText"] isEqualToString: mutable[i]]) {
                
                [month addObject:arr[j]];
            }
            
        }
        
        [self.dic setObject:month forKey:mutable[i]];

        
    }
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString *str=@"str";
    DrivingRecordCell  * cell =  [tableView dequeueReusableCellWithIdentifier:str];
    if (cell ==nil) {
        cell = [[DrivingRecordCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    [cell showInfo:dataArr[indexPath.section][@"waybills"][indexPath.row]];
    
    NSArray *arr = [self.dic allKeys];
    NSMutableDictionary *infoArr = (NSMutableDictionary *)self.dic[arr[indexPath.section]][indexPath.row];
    
    [cell showInfo:infoArr];
    
//        [cell showInfo:dataArr[indexPath.section]];

    return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSArray *arr = [self.dic allKeys];
    return arr.count;
    
}




-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSArray *arr = [self.dic allKeys];
    return [self.dic[arr[section]] count];
    
//    return [dataArr count];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 90*kHeight;

}



-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 43*kHeight;
}


-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    NSArray *arr = [self.dic allKeys];

    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Width, 43*kHeight)];
    view.backgroundColor = WhiteColor;
    
    NSString * string = [NSString stringWithFormat:@"%@",arr[section]];

    UILabel * timelabel = [self createUIlabel:string andFont:FontOfSize13 andColor:AddCarColor];
    [view addSubview:timelabel];
    
    [timelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(view.mas_left).with.offset(18*kWidth);
        make.centerY.mas_equalTo(view.mas_top).with.offset(21.5*kHeight);
    }];

    UIView * viewline = [[UIView alloc]init];
    viewline.backgroundColor = LineGrayColor;
    [view addSubview:viewline];
    [viewline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(view.mas_bottom);
        make.left.mas_equalTo(view.mas_left);
        make.size.mas_equalTo(CGSizeMake(Main_Width, 0.5));
    }];
    return view;
    
}

-(UILabel*)createUIlabel:(NSString *)title andFont:(CGFloat)font andColor:(UIColor*)color {
    UILabel * label =[[UILabel alloc]init];
    label.text = title;
    label.textColor = color;
    UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:font];CGSize size = [label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
    CGFloat nameH = size.height;
    CGFloat nameW = size.width;
    label.textAlignment = NSTextAlignmentRight;
    label.frame =CGRectMake(0, 0, nameW, nameH);
    label.font = Font(font);
    return label;
}



-(void)viewWillAppear:(BOOL)animated{
    [TabBar setTabBarHidden:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
